package org.wattdepot.cli.command;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.cli.processor.CommandLineInterface;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Holds method to create a page with a chart of power statistics.
 * 
 * @author Kendyll Doi, Kimberly Heu
 * 
 */
public class WattChart {
/**
 * creates a page with a chart of power statistics.
 *
 * @param type the type consumed or generated that will be observed
 * @param source the source that will be observed
 * @param startday the day observation stops
 * @param endday the day observation ends
 * @param interval the minutes in which data will be gathered
 * @param file the file that will contain the data gathered
 * @param client the client which holds the sources for record
 * @return returns a statement reporting file creation
 */
  public static String wattChart(String type, String source, String startday, String endday,
      int interval, String file, WattDepotClient client) {
    String output = null;
    int maxUriLength = 2048;
    StringBuffer chartUri = new StringBuffer(maxUriLength);
    chartUri.append("http://chart.apis.google.com/chart?chs=250x100&cht=lc&chd=t:");

    if (interval <= 0) {
      return "interval must be greater than 0";
    }

    try {
      XMLGregorianCalendar starttime = CommandLineInterface.createTstamp(startday);
      XMLGregorianCalendar endtime = CommandLineInterface.createTstamp(endday);
      if (starttime == null) {
        return "Time argument not correct";
      }
      if (endtime == null) {
        return "Time argument not correct";
      }
      XMLGregorianCalendar timestamp = starttime;
      double power = 0.0;
      double maxPower = Double.MIN_VALUE;
      double minPower = Double.MAX_VALUE;
      if (starttime.compare(endtime) > 0) {
        return "End date cannot occur before start date";
      }

      while (Tstamp.lessThan(timestamp, endtime)) {
        if (type.equalsIgnoreCase("generated")) {
          power = client.getPowerGenerated(source, timestamp) / 1000000;
        }
        else if (type.equalsIgnoreCase("consumed")) {
          power = client.getPowerConsumed(source, timestamp) / 1000000;
        }
        else {
          return "Error in type: use consumed or generated.";
        }
        chartUri.append(String.format("%.1f,", power));
        if (power < minPower) {
          minPower = power;
        }
        if (power > maxPower) {
          maxPower = power;
        }
        timestamp = Tstamp.incrementMinutes(timestamp, interval);
      }
      // Delete trailing ','
      chartUri.deleteCharAt(chartUri.length() - 1);
      chartUri.append(String.format("&chds=%.1f,%.1f&chxt=y&chxr=0,%.1f,%.1f", minPower, maxPower,
          minPower, maxPower));

      FileOutputStream fileOut = null;
      try {
        fileOut = new FileOutputStream(file);
      }
      catch (FileNotFoundException e) {
        return "Cannot create output stream to write " + file + " file.";
      }

      BufferedOutputStream writeOut = new BufferedOutputStream(fileOut);
      output =
          "<HTML><HEAD><TITLE>Wattdepot-Cli Chart - Made with Google</TITLE></HEAD><BODY>"
              + "<IMG SRC=" + chartUri + " /><br />Checking Power: " + type + "<br />Source: "
              + source + "<br />From: " + startday + " to " + endday + "<br />Sampling Every: "
              + interval + "minutes</BODY></HTML>";
      try {
        writeOut.write(output.getBytes());
        writeOut.flush();
        writeOut.close();
        fileOut.close();
      }
      catch (IOException e) {
        return "Error: an error occured while writing to file.";
      }

    }
    catch (ResourceNotFoundException e) {
      //e.printStackTrace();
      return "No data found for \"" + source + "\". It might not exist.";
    }
    catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return "An error has occured.";
    }

    return "File Created: " + System.getProperty("user.dir") + "\\" + file;
  }
}
